//
//  GXGroupManageController.m
//  YIChuSeller
//
//  Created by 田小椿 on 2018/12/1.
//  Copyright © 2018年 xiangshengjun. All rights reserved.
//

#import "GXGroupManageController.h"
#import "GXChangeGroupNameController.h"
#import "GXGroupFootView.h"
#import "GXMoreOperationController.h"
#import "GXMenuGroupModel.h"
@interface GXGroupManageController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView * groupTableView;
@property (nonatomic,strong)UIButton * rightItem;
@property (nonatomic,strong)NSMutableArray * dataArray;
@property (nonatomic,copy)NSString *storeId;
@property (nonatomic,copy)NSString *gruopNameStr;
@property (nonatomic,strong)NSMutableArray *moveArray;
@property (nonatomic,assign)BOOL moveType;//判断移动
@end
static NSString *const groupCell=@"GroupCell";
@implementation GXGroupManageController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestGroupRequsetData];
    [self creatAllView];
    _moveType = NO;
}
- (void)creatAllView
{
    self.title = @"分组管理";
    self.view.backgroundColor = kGlobalbgColor;
    [self.view addSubview:self.groupTableView];
    [self creatNavigitionRightItem];
}

#pragma 请求分组管理数据
- (void)requestGroupRequsetData
{
    self.storeId= [AccountTool sharedAccountTool].account.sotres[@"storeId"];
    [MenuContentManager selectMenuGroupWithStoreID:self.storeId success:^(id responseObject) {
        self.dataArray = [NSMutableArray arrayWithArray:responseObject];
        [self addGroupFooterView];
        [self.groupTableView reloadData];
    } fail:^(id responseObject) {
    }];

}
- (void)creatNavigitionRightItem
{
    UIButton * rightItem = [UIButton setButtonTitleNormal:@"新增" buttonTitlSelect:@"完成" buttonTintColor:[UIColor whiteColor] textFont:[UIFont systemFontOfSize:13]];
    [rightItem addTarget:self action:@selector(pressNewAddBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem = rightItem;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightItem];
}
- (void)pressNewAddBtn:(UIButton *)btn
{
    if (btn.selected) {
        self.groupTableView.editing = NO;
        btn.selected = NO;
        if (_moveType) {
            [self requestMoveDataSource];
        }
    }else
    {
        [self addNewGroupAlterView];
    }
}
#pragma 请求分组移动的数据
- (void)requestMoveDataSource
{
    _moveType = NO;
    NSMutableArray * changeArray = [NSMutableArray array];
    for (int i = 0; i<self.dataArray.count; i++) {//对选择后的数据进行dishesStor有序
       GXMenuGroupModel *model = self.dataArray[i];
        model.dishesStor= [NSString stringWithFormat:@"%d",i];
        NSMutableDictionary *contentDic = model.mj_keyValues;
        [changeArray addObject:contentDic];
    }
    [MenuContentManager moveMenuGroupWithStoreId:self.storeId dishesgropS:changeArray success:^(id responseObject) {
        if (responseObject) {
            MyLog(@"移动成功");
        }
    } fail:^(id responseObject) {
    }];
}

- (void)addNewGroupAlterView
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"添加分组" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入分组名称";
    }];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            if ([NSString isBlankString:alert.textFields.lastObject.text]) {
            [SVProgressHUD showErrorWithStatus:@"输入不能为空"];
            return ;
        }
        self.gruopNameStr =alert.textFields.lastObject.text;
            [self addGroupName];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)addGroupName
{
    [MenuContentManager addMenuGroupWithStoreID:self.storeId groupName:self.gruopNameStr success:^(id responseObject) {
        if (responseObject) {
            [self requestGroupRequsetData];
        }
    } fail:^(id responseObject) {
    }];
}

#pragma mark 创建TableView
- (UITableView *)groupTableView
{
    if (_groupTableView == nil) {
        _groupTableView=[[UITableView alloc] initWithFrame:CGRectMake(5,0,kUIScreenWidth-10,kUIScreenHeight-Height_NavBar-Height_TabBar) style:UITableViewStyleGrouped];
        _groupTableView.backgroundColor = kGlobalbgColor;
        _groupTableView.delegate=self;
        _groupTableView.dataSource=self;
        _groupTableView.sectionHeaderHeight = 20;
        _groupTableView.showsHorizontalScrollIndicator=NO;
        _groupTableView.showsVerticalScrollIndicator=NO;
        _groupTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    }
    return _groupTableView;
}
#pragma 添加底部试图
- (void)addGroupFooterView
{
    GXGroupFootView * footerView = [GXGroupFootView footView];
    footerView.frame = CGRectMake(0, kUIScreenHeight-Height_NavBar-45, kUIScreenWidth, 45);
    WeakSelf(weakSelf);
    footerView.moveButtonBlock = ^(UIButton * _Nonnull moveButton) {
        if ([moveButton.titleLabel.text isEqualToString:@"移动操作"]) {
            weakSelf.rightItem.selected = YES;
            weakSelf.groupTableView.editing = YES;
            [weakSelf.moveArray removeAllObjects];
        }else if ([moveButton.titleLabel.text isEqualToString:@"更多操作"]){
            GXMoreOperationController * moreVC =[[GXMoreOperationController alloc]init];
            moreVC.dataArray = self.dataArray;
            moreVC.deleteBolck = ^(GXMenuGroupModel * _Nonnull model) {
                [weakSelf.dataArray removeObject:model];
                [weakSelf.groupTableView reloadData];
            };
            [weakSelf.navigationController pushViewController:moreVC animated:YES];
        }
    };
    [self.view addSubview:footerView];
    
}

#pragma mark ---UITableViewDataSource UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:groupCell];
    cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:groupCell];
    GXMenuGroupModel * model =self.dataArray[indexPath.row];
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 2;
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    GXChangeGroupNameController * changeVC = [[GXChangeGroupNameController alloc]init];
    GXMenuGroupModel *model = self.dataArray[indexPath.row];
    changeVC.groupModel = model;
    WeakSelf(weakSelf);
    changeVC.refreshBlock = ^(GXMenuGroupModel * _Nonnull model) {
        [weakSelf.dataArray replaceObjectAtIndex:indexPath.row withObject:model];
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self.navigationController pushViewController:changeVC animated:YES];

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headerView = [[UIView alloc]init];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  UITableViewCellEditingStyleNone;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    GXMenuGroupModel * model = self.dataArray[sourceIndexPath.row];
    [self.dataArray removeObject:model];
    [self.dataArray insertObject:model atIndex:destinationIndexPath.row];
    _moveType = YES;
    [self.groupTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
}

@end
